package com.lagou.edu.utils;

import java.io.File;
import java.io.IOException;

import java.net.URL;

import java.util.*;

public class ScanClassUtils {

	/**
	 * Description: 获取rootPath的相关的根路径
	 * @return rootPath的相关的根路径
	 * @throws Exception
	 */


	/**
	 * 使用 IO扫描 Class文件
	 */
	public static List<String> getListClasses(String scanPath, List<String> classList) throws IOException {
		Enumeration<URL> resources = ScanClassUtils.class.getClassLoader().getResources("");
		URL rootUrl = resources.nextElement();
		String rootPath = rootUrl.getPath();
		File file = new File(scanPath);
		// 获取所有文件和文件夹
		File[] fileList = file.listFiles();
		if (classList == null ){
			classList = new ArrayList<>();
		}
		for (int i = 0; null != fileList && i < fileList.length; i++) {
			String path = fileList[i].getPath();
			// 如果是目录
			if (fileList[i].isDirectory()) {
				// 继续递归
				getListClasses(path,classList);
			}
			if (fileList[i].isFile()) {
				// 拼接类路径保存到集合中
				String classpath = path.replace(rootPath, "").replaceAll(".class", "")
						.replaceAll(File.separator, ".");
				classList.add(classpath);
			}
		}
		return classList;
	}

	/**
	 * 使用 所有类全命名来 初始化容器
	 *
	 * @throws Exception
	 */
	public static Map<String, Class<?>> doScanClasses(String packageName) throws Exception {
		Enumeration<URL> resources = ScanClassUtils.class.getClassLoader().getResources("");
		URL rootUrl = resources.nextElement();
		String rootPath = rootUrl.getPath();
		String scanPath = rootPath + packageName.replace(".", File.separator);
		List<String> nameList = getListClasses(scanPath,null);
		Map<String, Class<?>> map = new HashMap<>();
		if (nameList.size() > 0) {
			// 获取 所有类的类全名
			for (int i = 0; i < nameList.size(); i++) {
				String name = nameList.get(i);
				Class<?> clazzInfo = Class.forName(name);
				//接口 enum 注解的不需要加载到容器中
				if (!clazzInfo.isAnnotation() &&  !clazzInfo.isInterface() && !clazzInfo.isEnum() ) {
					// 初始化类对象 添加到容器中
					if (!map.containsKey(name)) {
						map.put(name, clazzInfo);
					}
				}
			}
		}else{
			throw new Exception("路径不存在！");
		}
		return map;
	}

	/**
	 * 测试
	 *
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		Map map = ScanClassUtils.doScanClasses("com.lagou.edu.service");
		System.out.println("@@@@@@@@@@@@@@");
		System.out.println(map);
	}

}
